import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class ServerGameCaro {

	public static final int LISTENING_PORT = 9999;
	
	public static void main(String[] args) {
		
		// Create a server socket for listening on port 9999
		// Tao server socket lang nghe tren port 9999
		
		ServerSocket serverSocket = null;
		try {
		
			serverSocket = new ServerSocket(LISTENING_PORT);
			System.out.println("--->> Server GameCaro is starting . . .");
		}
		catch (IOException ioe) {
			
			System.out.println("!!! Khong the lang nghe tren port " + LISTENING_PORT);
		}
		
		// Create a dispatcher
		// Tao dispatcher
		
		Dispatcher serverDispatcher = new Dispatcher();
		serverDispatcher.start();
		System.out.println("--->> ServerDispatcher is created.");
		
		// Accept and handle client connect
		// Chap nhan va xu ly ket noi tu client
		
		int stt = 1;
		while (true) {
			try {
			
			// Listening and accept client connect
			// Lang nghe va chap nhan ket noi
				
				Socket socket = serverSocket.accept();
				
				System.out.println("- There is a client has connected to our server with ip is " + socket.getInetAddress());
				
			// Handle client connect
			// Xu ly noi ket
				
				ClientInfo ci = new ClientInfo();
				ci.mSocket = socket;
				ci.mId = stt++;
				ci.status = true;
				ClientListener cl = new ClientListener(ci , serverDispatcher);
				ClientResponse cr = new ClientResponse(ci , serverDispatcher);
				cl.start();
				cr.start();
				ci.mClientListener = cl;
				ci.mClientResponse = cr;

				serverDispatcher.addClient(ci);
				serverDispatcher.addOnlineUser(ci.mId);
				
				System.out.println("- Process and add this client into ServerDispatcher successfully .");
			}
			catch (IOException ioe) {
				
				System.out.println("!!! Loi server !");
			}
		}
		
		
	}
}
